package com.example.securitymy.service.impl;

import com.example.securitymy.domain.ResponseResult;
import com.example.securitymy.service.VerificationCodeService;
import com.example.securitymy.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeServiceImpl.class);

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisCache redisCache;

    private static final String CODE_PREFIX = "verification:code:";
    private static final long CODE_EXPIRATION = 5; // 验证码有效期（分钟）
    // 发送验证码
    @Override
    public ResponseResult sendVerificationCode(String email) {
        // 生成6位随机验证码
        System.out.println("已经进入到了发送验证码service");
        String verificationCode = generateVerificationCode();
        System.out.println("===================验证码：==========================" + verificationCode);
        // 发送邮件d
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("3153618284@qq.com"); // 替换为你的邮箱
        message.setTo(email);
        message.setSubject("密码重置验证码");
        message.setText("您的验证码是: " + verificationCode + "\n该验证码" + CODE_EXPIRATION + "分钟内有效。");
        System.out.println(message);
        try {
            mailSender.send(message);
            // 将验证码存储到Redis，设置过期时间
            redisCache.setCacheObject(CODE_PREFIX + email, verificationCode, (int)CODE_EXPIRATION, TimeUnit.MINUTES);
            return new ResponseResult(200, "验证码已发送到您的邮箱");
        } catch (Exception e) {
            logger.error("验证码发送失败", e);
            return new ResponseResult(500, "验证码发送失败");
        }
    }
    //验证前端发来的验证码是否正确
    @Override
    public boolean verifyCode(String email, String code) {
        String storedCode = redisCache.getCacheObject(CODE_PREFIX + email);
        if (storedCode != null && storedCode.equals(code)) {
            // 验证成功后删除验证码
            redisCache.deleteObject(CODE_PREFIX + email);
            return true;
        }
        return false;
    }
    // 生成6位随机验证码
    private String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
} 